﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;

namespace iReaper
{
    public class GeoInfoManager
    {
        static LookupService service;

        public static void Init()
        {
            // Get GeoLiteCity.dat location
            string fileName = System.Web.Configuration.WebConfigurationManager.AppSettings["GeoData"];
            string geoPath = HttpContext.Current.Server.MapPath(fileName);
            service = new LookupService(geoPath, LookupService.GEOIP_MEMORY_CACHE | LookupService.GEOIP_STANDARD);

            TimerManager.OnTimer += new EventHandler(OnTimer);    
        }

        private static void OnTimer(object sender, EventArgs e)
        {
            DataManager.UpdateGeoInfo();
        }

        public static void UpdateTableSet(DataSet ds)
        {
            DataTable table = ds.Tables[0];
            foreach (DataRow dr in table.Rows)
            {
                long ip = (long)dr[0];
                Location lc = service.getLocation(new System.Net.IPAddress(ip));
                if (lc != null)
                {
                    dr[1] = lc.city;
                    dr[2] = lc.region;
                }
            }
        }
    }
}
